<template>
    <div class="container" v-cloak>
        <div class="blurBg" :style="{background:'url('+blurBg+') 0 0 no-repeat'}"></div>
        <div class="dataInfo">
            <div class="selectStudent font12 hasStudent" flex="main:justify cross:center">
                <input class="font12 title" placeholder="请输入作业标题" flex-box="1" maxlength="20" v-model="title">
                <div class="opacity5 font10 uploadNum" flex-box="0"><span v-text="title.length"></span>/20</div>
            </div>
            <div class="bottomLine"></div>
            <div class="selectStudent font12 hasStudent" flex="main:justify cross:center"
                 @click="getDatePicker(new Date(`${new Date().getFullYear()}/${new Date().getMonth()+1}/${new Date().getDate()} 00:00:00`).getTime(),0,beginTime*1000,true)">
                <div class="opacity5 font12" flex-box="0">开始时间</div>
                <div class="studentName" v-text="new Date(beginTime*1000).Format('M月d日')" flex-box="1"
                     flex="main:right"></div>
                <div class="rightIcon" flex-box="0"></div>
            </div>
            <div class="bottomLine"></div>
            <div class="selectStudent font12 hasStudent" flex="main:justify cross:center"
                 @click="getDatePicker(beginTime*1000,0,new Date(`${new Date(endTime*1000).getFullYear()}/${new Date(endTime*1000).getMonth()+1}/${new Date(endTime*1000).getDate()} 00:00:00`).getTime(),false)">
                <div class="opacity5 font12" flex-box="0">结束时间</div>
                <div class="studentName" v-text="new Date(endTime*1000).Format('M月d日')" flex-box="1"
                     flex="main:right"></div>
                <div class="rightIcon" flex-box="0"></div>
            </div>
            <div class="bottomLine"></div>
            <div class="selectStudent font12 hasStudent" flex="main:justify cross:center"
                 @click="getPicker(taskCycleArr,taskCycleIndex)">
                <div class="opacity5 font12" flex-box="0">作业提交周期</div>
                <div class="studentName" v-text="taskCycle.text" flex-box="1"
                     flex="main:right"></div>
                <div class="rightIcon" flex-box="0"></div>
            </div>
            <div class="bottomLine"></div>
            <div class="inputModel">
                <div class="inputTitle Semibold font13">作业内容</div>
                <textarea class="titleInput" ref="textarea" placeholder="请输入作业内容" v-model="content"
                          maxlength="2000"></textarea>
                <div class="inputLimit"><span v-text="content.length"></span>/2000</div>
            </div>
            <div class="uploadModel">
                <div class="uploadTitle Semibold font13" flex="cross:bottom">
                    <div>作业展示</div>
                    <div class="font10 uploadNum">(<span v-text="uploadList.length"
                                                         :style="{color:uploadList.length>0?'#1dc6b4':''}"></span>/9)
                    </div>
                </div>
            </div>
            <ul class="uploadList">
                <li class="uploadAdd" flex="main:center cross:center" v-if="uploadList.length<9" @click="showAdd()">
                    <img src="../../images/addIcon.png" class="addIcon"/>
                </li>
                <li flex v-for="(pic,index) in uploadList" class="picesWrap" :key="pic"
                    @click="seePicesItem(index)">
                    <div class="audioWrapper" v-if="pic.datatype==2">
                        <img src="../../images/audioBg.png"/>
                        <div class="audioTime" flex="main:center cross:center">
                            <span v-text="pic.datatime>=60?parseInt(pic.datatime/60):0" flex-box="0"></span>
                            <span flex-box="0">:</span>
                            <span v-text="parseInt(pic.datatime%60)>=10?parseInt(pic.datatime%60):'0'+parseInt(pic.datatime%60)"
                                  flex-box="0"></span>
                        </div>
                    </div>
                    <img :src="pic.datathumbnail" v-if="pic.datatype!=2">
                    <img src="../../images/play.png" class="play" v-if="pic.datatype==3"/>
                    <div class="removeIcon" @click.stop="removeItem(index)" v-if="canUploadClick"></div>
                </li>
            </ul>
        </div>
        <div class="allSendBtn"  flex="main:center cross:center"
             @click="sendMultiwork">发送
        </div>
        <add-model ref="addModel" @addFuc="changeFile"></add-model>
        <div class="uploadWrapper" v-if="!canUploadClick"></div>
    </div>
</template>
<script type="text/babel">
    import API from '../../../api/api.js'
    import {domain} from '../../../api/api.js'
    import addModel from '../../../components/addModel.vue'
    import studentList from '../../../components/studentList.vue'

    const api = new API();
    export default {
        data() {
            return {
                title:new Date().Format('M月d日') +' 打卡作业',
                //作业标题
                taskCycleArr: [
                    {
                        text: '每天提交',
                        value: 1
                    },
                    {
                        text: '每周提交',
                        value: 2
                    },
                    {
                        text: '每月提交',
                        value: 3
                    }
                ],
                //提交周期选择列表
                taskCycle: {
                    text: '每天提交',
                    value: 1
                },
                //当前选择提交周期
                taskCycleIndex: 0,
                //当前选择提交索引
                content: '',
                //作业内容
                uploadList: [],
                //作业附件
                classId: this.$route.query.classId ? this.$route.query.classId : '',
                //班级Id
                domain: domain,
                //域名
                imgKeys: [],
                //作业附件客户端传递的key
                beginTime: new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} 00:00:00`).getTime() / 1000,
                //作业开始时间
                endTime: new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} 23:59:59`).getTime() / 1000,
                //作业结束时间
                canUploadClick: true,
                //是否可以提交作业(防止多次请求发布接口)
                titleCheck: /[\ud800-\udbff][\udc00-\udfff]/
            }
        },
        mounted() {
            this.$util.jsBridgeCallBack('jsLeftAction', this.closeWebView);
            this.$nextTick(function () {
                setTimeout(() => {
                    this.propsTitle();
                }, 300);
                document.documentElement.scrollTop = 1;
                document.body.scrollTop = 1;
            })
        },
        components: {
            addModel,
            studentList
        },
        methods: {
            /**
             * @describe jsBridge 时间选择器格式化
             *
             * @param    date 时间选择器返回时间戳
             *
             * @param    ifBegin 是否是开始时间选择器(true为开始，false为结束)
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */

            datePickerFormat(date, ifBegin) {
                if (ifBegin) {
                    this.beginTime = new Date(`${new Date(date).getFullYear()}/${new Date(date).getMonth() + 1}/${new Date(date).getDate()} 00:00:01`).getTime() / 1000;
                    if (this.beginTime > this.endTime) {
                        this.endTime = new Date(`${new Date(this.beginTime * 1000).getFullYear()}/${new Date(this.beginTime * 1000).getMonth() + 1}/${new Date(this.beginTime * 1000).getDate()} 23:59:59`).getTime() / 1000;
                    }
                } else {
                    this.endTime = new Date(`${new Date(date).getFullYear()}/${new Date(date).getMonth() + 1}/${new Date(date).getDate()} 23:59:59`).getTime() / 1000;
                }
            },
            /**
             * @describe jsBridge 时间选择器
             *
             * @param    start 开始时间
             *
             * @param    end 结束时间
             *
             * @param    ifBegin 是否是开始时间选择器(true为开始，false为结束)
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */

            getDatePicker(start, end, now, ifBegin) {
                this.$util.JsBridge('getDatePicker', {
                    minDate: start,
                    maxDate: end,
                    nowDate: now
                }, (res) => {
                    this.datePickerFormat(res, ifBegin)
                })
            },
            /**
             * @describe jsBridge 选择器
             *
             * @param    pickerList 选择器内容(类型为Array)
             *
             * @param    pickerIndex 选择器内容时索引
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            getPicker(pickerList, pickerIndex) {
                let picker = [];
                pickerList.forEach((el, index) => {
                    picker.push(el.text);
                });
                this.$util.JsBridge('getPicker', {
                    pickerList: picker,
                    pickerIndex: pickerIndex ? pickerIndex : 0
                }, (res) => {
                    //res为选择器选中索引
                    this.taskCycleIndex = parseInt(res);
                    this.taskCycle = this.taskCycleArr[this.taskCycleIndex];
                }, true)
            },
            /**
             * @describe jsBridge 关闭webView
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            closeWebView() {
                this.$util.JsBridge('closeWebView', {}, () => {
                })
            },
            /**
             * @describe 显示添加附件组件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            showAdd() {
                this.$refs.addModel.addShow = true;
            },
            /**
             * @describe 关闭添加附件组件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            closeAdd() {
                this.$refs.addModel.addShow = false;
            },
            /**
             * @describe 显示添加学员组件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            showStudent() {
                this.$refs.studentList.showStudent();
            },
            /**
             * @describe jsBridge 传递title
             *
             * @date     2017-8-3
             *
             * @param    title 标题
             *
             * @author   langwenqi
             */
            propsTitle() {
                this.$util.JsBridge('propsTitle', {
                    title: '打卡作业',
                }, (res) => {
                })
            },
            /**
             * @describe jsBridge 查看添加附件大图
             *
             * @date     2017-8-3
             *
             * @param    index 附件索引
             *
             * @author   langwenqi
             */
            seePicesItem(index) {
                this.$util.JsBridge('seePicesItem', {
                    picItemIndex: index
                }, (res) => {
                })
            },
            /**
             * @describe 删除附件
             *
             * @date     2017-8-3
             *
             * @param    index 附件索引
             *
             * @author   langwenqi
             */
            removeItem(index) {
                this.$delete(this.uploadList, index);
                this.$util.JsBridge('removePicesItem', {
                    picItemIndex: index
                }, (res) => {
                })
            },
            /**
             * @describe 客户端上传文件
             *
             * @date     2017-8-3
             *
             * @param    picItemCount 附件上传限制张数
             *
             * @param    type 附件上传类型
             *
             * @param    appType APP_MULTI_WORK
             *
             * @author   langwenqi
             */
            changeFile(type) {
                //TODO:客户端上传文件
                if (9 - this.uploadList.length > 0) {
                    this.$util.JsBridge('getPicesList', {
                        picItemCount: 9 - this.uploadList.length,
                        showType: type,
                        appType: 'APP_MULTI_WORK'
                    }, (res) => {
                        this.changeFileCallBack(res);
                        this.closeAdd()
                    })
                } else {
                    this.$toast('您最多只能上传9个附件');
                }
            },
            /**
             * @describe 客户端上传文件
             *
             * @date     2017-8-3
             *
             * @param    res 附件的key(类型Array)
             *
             * @author   langwenqi
             */
            changeFileCallBack(res) {
                this.imgKeys = res;
                for (let i = 0; i < res.length; i++) {
                    this.getImgInfo(res[i])
                }
            },
            /**
             * @describe 通过key获取客户端文件
             *
             * @date     2017-8-3
             *
             * @param    rs 单个附件的key
             *
             * @author   langwenqi
             */
            getImgInfo(rs) {
                this.$util.JsBridge('getImgInfo', {
                    fileKey: rs
                }, (res) => {
                    if (res.datathumbnail && res.datathumbnail.indexOf('data:image/png;base64') == -1) {
                        res.datathumbnail = 'data:image/png;base64,' + res.datathumbnail;
                    }
                    this.uploadList.push(res);
                })
            },
            /**
             * @describe 发布校验
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            check() {
                if (this.title === '') {
                    this.$toast('请输入作业标题');
                    return false
                } else if (this.titleCheck.test(this.title)) {
                    this.$toast('标题内容不能包含表情');
                    return false;
                } else if (this.endTime < this.beginTime) {
                    this.$toast('开始时间不能大于结束时间');
                    return false
                } else if (this.content === ''&&this.uploadList.length<=0) {
                    this.$toast('请输入作业内容或添加附件');
                    return false
                }
                return true
            },
            /**
             * @describe 发布作业
             *
             * @param    title作业标题
             *
             * @param    classId班级id
             *
             * @param    type作业提交周期
             *
             * @param    content作业内容
             *
             * @param    beginTime作业开始时间
             *
             * @param    beginTime作业结束时间
             *
             * @param    picNum附件个数
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            sendMultiwork() {
                if (this.check()) {
                    if (this.canUploadClick) {
                        this.canUploadClick = false;
                        const content = this.$util.utf16toEntities(this.content).replace(/\n|\r\n/g, "<br>").replace(/[ ]/g, "&nbsp;");
                        let params = {
                            title: this.title,
                            classId: this.classId,
                            type: this.taskCycle.value,
                            content: content,
                            beginTime: this.beginTime,
                            endTime: this.endTime,
                            picNum: this.uploadList.length
                        };
                        let response = api.sendMultiwork(params);
                        response.then((res) => {
                            if (res.code === 200) {
                                if (this.uploadList.length > 0) {
                                    this.$util.JsBridge('sendFinish', {
                                        taskTid: res.rs.taskTid,
                                        appType: 'APP_MULTI_WORK',
                                        content: this.content,
                                        taskName: '打卡作业',
                                        taskImageURL: this.domain + 'www/static/images/app_icon_v200/dakazuoye-3x.png'
                                    }, () => {
                                    })
                                } else {
                                    this.$toast('成功', true);
                                    setTimeout(() => {
                                        this.closeWebView();
                                    }, 1000);
                                }
                            } else {
                                this.$toast(res.msg);
                                this.canUploadClick = true;
                                this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/add',api:'sendMultiwork',success:false,data:res}));
                            }
                        }).catch(() => {
                            this.canUploadClick = true;
                            this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/add',api:'sendMultiwork',success:false,data:'网络异常'}));
                        })
                    } else {
                        this.$toast('上传中，请稍后');
                    }
                }
            }
        }
    }
</script>
<style scoped lang="scss">
    .container {
        width: 100%;
        height: 100%;
        background: #000;
        position: relative;
    }

    .selectStudent {
        padding: 0.19rem 0.12rem 0.1rem 0.12rem;
        .title {
            color: #fff;
            height: 100%;
            background: transparent;
        }
        .studentWrapper {
            margin-right: 0.07rem;
            height: 0.34rem;
            width: 0.34rem;
            border-radius: 100%;
            overflow: hidden;
            img {
                height: 100%;
                width: 100%;
                -o-object-fit: cover;
                object-fit: cover;
            }
        }
        .studentName {
            padding-right: 0.07rem;
        }
        .rightIcon {
            height: 0.1rem;
            width: 0.1rem;
            background: url("../../images/iconMore.png") no-repeat right center/contain;
        }
    }

    .bottomLine {
        background: rgba(255, 255, 255, .2);
        width: 3.5rem;
        height: 1px;
        margin: 0 auto;
    }

    .inputModel {
        height: 1.83rem;
        width: 100%;
        padding-bottom: 0.13rem;
        border-bottom: 0.12rem solid rgba(0, 0, 0, 0.5);
    }

    .inputTitle {
        padding: 0.12rem 0 0.12rem 0.12rem;
    }

    .inputLimit {
        opacity: 0.5;
        font-size: 0.1rem;
        text-align: right;
        margin-right: 0.12rem;
    }

    .titleInput {
        width: 100%;
        padding: 0 0.12rem;
        background: transparent;
        font-size: 0.13rem;
        color: #ffffff;
        height: 1rem;
    }

    .uploadTitle {
        padding: 0.17rem 0 0.12rem 0;
    }

    .uploadAdd {
        border: 1px dashed #ccd2da;
        width: 0.8rem;
        height: 0.8rem;
    }

    .uploadModel {
        padding-left: 0.12rem;
    }

    .addIcon {
        width: 0.23rem;
        height: 0.23rem;
    }


    .picesWrap {
        background: #d8d8d8;
        position: relative;
        width: 0.8rem;
        height: 0.8rem;
        overflow: hidden;
        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            -o-object-fit: cover;
        }
    }

    .uploadList {
        padding-left: 0.12rem;
        padding-bottom: 1rem;
        padding-left: 0.12rem;
        overflow: hidden;
        li {
            position: relative;
            margin-bottom: 0.1rem;
            margin-right: 0.1rem;
            float: left;
        }
    }

    .inputWrap {
        width: 2.7rem;
        height: 0.81rem;
        position: relative;
        background: rgba(250, 251, 255, .1);
        textArea {
            width: calc(100% - 0.24rem);
            height: 100%;
            background: transparent;
            padding: 0.08rem 0 0 0.08rem;
            font-size: 0.12rem;
            color: #fff;
        }
    }

    .removeIcon {
        width: 0.18rem;
        height: 0.18rem;
        position: absolute;
        right: 0.04rem;
        top: 0.04rem;
        background: url("../../images/delete.png") no-repeat center center/cover;
    }

    .uploadNum {
        opacity: 0.5;
        margin-left: 0.08rem;
    }

</style>
